package com.drondea.testclient.handler.smpp;

import cn.hutool.core.util.StrUtil;
import com.drondea.sms.message.smpp34.SmppSubmitSmResponseMessage;
import com.drondea.sms.type.SmppConstants;
import com.drondea.testclient.handler.AbstractSubmitResponseHandler;
import com.drondea.testclient.panel.SmppPanel;
import com.drondea.testclient.util.counter.SmppAtomicUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试收到的短信回应
 *
 * @author liuyanning
 */
@Sharable
@Slf4j
public class SmppSubmitSmResponseHandler extends AbstractSubmitResponseHandler<SmppSubmitSmResponseMessage> {
    private static final SmppPanel PANEL = SmppPanel.getInstance();

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, SmppSubmitSmResponseMessage msg) {
        log.debug("SmppSubmitResponseMessage : {} : Status: {} MessageId: {}", msg.getSequenceId(), msg.getHeader().getCommandStatus(), msg.getMessageId());
        PANEL.responseCountLabel.setText(StrUtil.format("响应数量: {}", SmppAtomicUtil.RESPONSE_COUNT.incrementAndGet()));
        long result = msg.getHeader().getCommandStatus();
        if (result == SmppConstants.STATUS_OK) {
            // 此处的状态只是短信提交结果，不代表实际发送是否成功,实际是否成功需要通过回执结果来判断
            PANEL.successCountLabel.setText(StrUtil.format("提交成功: {}", SmppAtomicUtil.SUCCESS_COUNT.incrementAndGet()));
        } else {
            PANEL.failCountLabel.setText(StrUtil.format("提交失败: {}", SmppAtomicUtil.FAIL_COUNT.incrementAndGet()));
        }

        // 当响应数量=发送数量时，设置结束时间
        if (SmppAtomicUtil.SEND_COUNT.get() == SmppAtomicUtil.RESPONSE_COUNT.get()) {
            calAvgSubmitSpeed(PANEL, SmppAtomicUtil.SEND_COUNT.get() - PANEL.submitCountBefSend);
        }
    }

}
